<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
</head>
<style>
    .box1 {
        width: 100px;
        height: 100px;
        background-color: aqua;
        position: absolute;
    }
    
    .box2 {
        width: 100px;
        height: 100px;
        background-color: pink;
        position: absolute;
        left: 600px;
    }
</style>

<body>
    <div class="box1"></div>
    <div class="box2"></div>
    <script>
        // 检测碰撞必须是2个元素，宽高一致
        // 获取元素
        var obox1 = document.querySelector(".box1");
        var obox2 = document.querySelector(".box2");
        // 按下box1
        obox1.onmousedown = function(e) {
            console.log(this);
            // 获取按下的值
            var x = e.clientX - this.offsetLeft;
            console.log(x);
            var y = e.clientY - this.offsetTop;
            console.log(y);
            // 移动
            this.onmousemove = function(e) {
                // 获取移动的值
                var xx = e.clientX;
                console.log(xx);
                var yy = e.clientY;
                console.log(yy);

                // 拖动框框移动
                this.style.left = xx - x + "px";
                this.style.top = yy - y + "px";

                // 检测碰撞
                // 获取第一个框离左边的距离
                var leonx = obox1.offsetLeft;
                var leony = obox1.offsetTop;
                console.log(leonx);
                console.log(leony);

                // 获取第二个框离左边的jul
                var letwx = obox2.offsetLeft;
                var letwy = obox2.offsetTop;
                console.log(letwx);
                console.log(letwy);
                if (
                    Math.abs(letwx - leonx) <= this.offsetWidth &&
                    Math.abs(letwy - leony) <= this.offsetHeight
                ) {
                    console.log("撞了");
                }
            };
        };
        document.onmouseup = function() {
            obox1.onmousemove = "";
        };
    </script>
</body>

</html>